package com.leyou.cart.interceptor;

import com.leyou.auth.pojo.UserInfo;
import com.leyou.auth.util.JwtUtils;
import com.leyou.cart.config.JwtProperties;
import com.leyou.common.utils.CookieUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    private JwtProperties props;

    private static final ThreadLocal<UserInfo> tl = new ThreadLocal<>();

    public UserInterceptor(JwtProperties props) {
        this.props = props;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 获取 cookie
        String token = CookieUtils.getCookieValue(request, props.getCookieName());
        try {
            // 解析 token
            UserInfo user = JwtUtils.getInfoFromToken(token, props.getPublicKey());
            // 传递 user
            // request.setAttribute("user", user);

            tl.set(user);

            return true;
        } catch (Exception e) {
            log.error("[购物车服务] 解析用户身份失败。", e);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 业务完成，清空数据
        tl.remove();
    }

    public static UserInfo getUserInfo() {
        return tl.get();
    }
}
